package com.tianheng.modbus.service;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**************************************************
 * copyright (c) 2020, peng.cao@tianheng-uestc.com All Rights Reserved.
 * created by peng.cao
 * date:       2020/7/10 0010
 * since:      1.0.0.1
 * description:
 *
 **************************************************/
public class InBoundHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("客户端"+ctx.channel().remoteAddress()+"接入服务器了");
        TCPServerNetty.getMap().put(getIPString(ctx), ctx.channel());

    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("来自设备"+getIPString(ctx)+"返回的数据是"+msg);

    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        TCPServerNetty.getMap().remove(getIPString(ctx));
        System.out.println("来自设备"+getIPString(ctx)+"移除服务");
    }


    public static String getIPString(ChannelHandlerContext ctx){
    String ipString = "";
    String socketString = ctx.channel().remoteAddress().toString();
    int colonAt = socketString.indexOf(":");
    ipString = socketString.substring(1, colonAt);
    return ipString;
}

}
